import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

public class BreakpointDownload {
    public static void main(String[] args) throws Exception {
        String strURL = "http://localhost:8080/ArcSyncHttpDownloadServlet";
        URL downUrl = new URL(strURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) downUrl.openConnection();
        if (httpURLConnection.getResponseCode() == 200) {
            int part_count = 10;
            int contentLength = httpURLConnection.getContentLength();
            System.out.println("httpURLConnection.getContentLength():" + httpURLConnection.getContentLength());
            int firstLength = contentLength / part_count;
            System.out.println("firstLength():" + firstLength);
            httpURLConnection.disconnect();
            for (int i = 1; i < part_count + 1; i++) {
                File saveFile = new File("D:/BaiduNetdiskDownload", String.format("08_queue模拟1.mp4", i));
                if (i == part_count) {
                    download(saveFile.getName(), saveFile.getParent(), strURL, (i - 1) * firstLength, contentLength);
                } else {
                    download(saveFile.getName(), saveFile.getParent(), strURL, (i - 1) * firstLength, firstLength * i);
                }

            }
        }
    }

    public static void download(String fileName, String filePath, String remoteUrl, long start, long end) {
        byte[] buf = new byte[10240];
        HttpURLConnection httpURLConnection;
        URL url;
        BufferedInputStream bis;
        int size;
        RandomAccessFile rndFile;
        // 下载文件
        try {
            url = new URL(remoteUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置User-Agent
            httpURLConnection.setRequestProperty("User-Agent", "Net");
            // 设置续传开始
            httpURLConnection.setRequestProperty("Range", "bytes=" + start + "-" + end);
             // 获取输入流
            bis = new BufferedInputStream(httpURLConnection.getInputStream());
            rndFile = new RandomAccessFile(filePath + "\\" + fileName, "rw");
            rndFile.seek(0);
            int i = 0;
            while ((size = bis.read(buf)) != -1) {
                rndFile.write(buf, 0, size);
                i++;
            }
            System.out.println("i=" + i);
            httpURLConnection.disconnect();
            bis.close();
            rndFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
